package com.lg.io.zero_copy;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;

@Slf4j
public class Base {
    @SneakyThrows
    public static void main(String[] args) {

        try {
            String path = "C:\\Users\\admin\\Desktop\\temp";
            String inPath = "C:\\Users\\admin\\Desktop\\read";
            File chunkFile = new File(path);
            if (!chunkFile.exists()) {
                chunkFile.createNewFile();
            }

            FileChannel outchannel = new FileOutputStream(chunkFile, true).getChannel();
            FileLock outlock = null;
            while (outlock == null) {
                try {
                    outlock = outchannel.tryLock();
                    log.info("获取锁成功");
                } catch (Exception e) {
                    log.info("等待解锁");
                }
            }

            File inFile = new File(inPath);
            FileInputStream fileInputStream = new FileInputStream(inFile);
            FileChannel inChannel = fileInputStream.getChannel();
            outchannel.transferFrom(inChannel,0,inChannel.size());

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}
